
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common'
import { Request, Response } from 'express'
import * as moment from 'moment';

interface ExceptionResponse {
    message: string;
    [key: string]: any;
}

@Catch(HttpException)
export class HttpFilter implements ExceptionFilter {
    catch(exception: HttpException, host: ArgumentsHost) {
        const ctx = host.switchToHttp()
        const request = ctx.getRequest<Request>()
        const response = ctx.getResponse<Response>()

        const statusCode = exception.getStatus()

        const exceptionResponse = exception.getResponse() as ExceptionResponse;
        let message: string;
        if (typeof exceptionResponse === 'object') {
            message = Array.isArray(exceptionResponse.message) ? exceptionResponse.message.join('; ') : exceptionResponse.message;
        } else {
            message = exceptionResponse;
        }

        response.status(statusCode).json({
            message,
            statusCode,
            success: false,
            time: moment().format("YYYY-MM-DD HH:mm:ss"),
            path: request.url,
        })
    }
}